<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="media-src 'self' file: data: blob: filesystem:; media-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"/>
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Live</title>
  </head>
  <body>

    <div class="dmdiv">
      <div class="dmtdiv">弹幕</div>
    </div>
    <video name = "videoElement" class="centeredVideo" onclick="playergo()"></video>
    <button id="gobtn" class="playbtn" onclick="playergo()">点击播放</button>
    <div id="headerdiv" style="-webkit-app-region: drag">!</div>
    <script src="./flv.js"></script>
    <script>
      var dmdiv = document.getElementsByClassName('dmdiv')[0]
      var dmli = []
      var roomid = getQueryVariable("id")
      //var roomid ='23058'
      var checkBoxFields = ['isLive', '', 'hasAudio', 'hasVideo']
      var streamURL = 'https://api.live.bilibili.com/room/v1/Room/playUrl?cid='+roomid+'&qn=0&platform=web'
      var player = ''
      var i;
      var isgo = true
      var httpRequest = new XMLHttpRequest()//第一步：创建需要的对象
      httpRequest.open('GET', streamURL, true) //第二步：打开连接
      httpRequest.setRequestHeader("Content-type","application/json");//设置请求头
      httpRequest.send()//发送请求
      /**
       * 获取数据后的处理程序
       */
      httpRequest.onreadystatechange = function () {//请求后的回调接口，可将请求成功后要执行的程序写在其中
          if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
              var json = JSON.parse(httpRequest.responseText);//获取到服务端返回的数据
              console.log(json.code)
              if (json.code === 0) {
                try {
                  play(json.data.durl[0].url)
                } catch (error) {
                  window.alert('播放失败')
                }
              }else{
                window.alert(JSON.stringify(json))
              }
          }
      }
      dm()

      function play(url) {
        var mediaDataSource = {
          type: 'flv',
          isLive: true,
          hasAudio: true,
          hasVideo: true,
          url: url,
        }
        player = flvjs.createPlayer(mediaDataSource, {
            enableWorker: false,
            lazyLoadMaxDuration: 3 * 60,
            seekType: 'range',
        })
        var element = document.getElementsByName('videoElement')[0]
        player.attachMediaElement(element)
        player.load()
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        document.getElementById("gobtn").dispatchEvent(e)
      }
      
      function playergo() {
        if (isgo) {
          player.play()
          document.getElementById('gobtn').className = 'playbtngo'
          console.log('play')
          isgo = false
        }
      }
      
      function getQueryVariable(variable)
      {
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            for (var i=0;i<vars.length;i++) {
                    var pair = vars[i].split("=");
                    if(pair[0] == variable){return pair[1];}
            }
            return(false);
      }
      
      function dm() {
        var dmhttpRequest = new XMLHttpRequest()//第一步：创建需要的对象
        /**
         * 获取数据后的处理程序
         */
        dmhttpRequest.onreadystatechange = function () {//请求后的回调接口，可将请求成功后要执行的程序写在其中
          var fl = true
          if (dmhttpRequest.readyState == 4 && dmhttpRequest.status == 200) {//验证请求是否发送成功
            var json = JSON.parse(dmhttpRequest.responseText);//获取到服务端返回的数据
            if (json.code === 0) {
              try {
                for (let index = 0; index < json.data.room.length; index++) {
                  fl = true
                  const element = json.data.room[index];
                  for (let a = 0; a < dmli.length; a++) {
                    const d = dmli[a];
                    if (d.timeline === element.timeline && d.uid === element.uid) {
                      fl = false
                      break
                    }
                  }
                  if (fl) {
                    console.log(element)
                    dmli.push(element)
                    var dmtdiv = document.createElement("div")
                    dmtdiv.innerText = '['+element.nickname+']:'+element.text
                    dmtdiv.className = 'dmtdiv'
                    dmdiv.appendChild(dmtdiv)
                    if (dmli.length > 20) {
                      dmli.shift()
                    }
                    removedm()
                  }
                }
              } catch (error) {
                console.log(error)
              }
            }
          }
          if (dmhttpRequest.readyState == 4) {
            setTimeout('dm()',1000)
            dmhttpRequest.abort()
          }
        }
        dmhttpRequest.open('POST', 'https://api.live.bilibili.com/ajax/msg', true) //第二步：打开连接
        dmhttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");//设置请求头
        let formData = new FormData()
        formData.append('roomid', roomid)  
        dmhttpRequest.send('roomid='+roomid)//发送请求
        dmhttpRequest
      }

      function removedm() {
        if (document.body.scrollHeight > window.innerHeight) {
          dmdiv.removeChild(document.getElementsByClassName('dmtdiv')[0])
          removedm()
        }
      }
    </script>
  </body>
  <style>
    html,body{
      height: 100%;
      margin: 0;
    }
    video{
      /* width: 70%; */
      width: 80%;
      height: 100%;
      margin: 0;
      background-color: black;
    }
    .dmdiv{
      margin: 0;
      border: 0;
      padding: 0;
      height: 100%;
      max-height: 100%;
      width: 20%;
      background-color: azure;
      float: right;
    }
    .playbtn{
      margin: 0;
      border: 0;
      padding: 0;
      bottom: 50%;
      left: 50%;
      position:absolute;
      color: rgb(117, 219, 214);
    }
    .playbtngo{
      margin: 0;
      border: 0;
      padding: 0;
      bottom: 50%;
      left: 50%;
      position:absolute;
      color: rgb(117, 219, 214);
      opacity: 0;
    }
    .dmtdiv{
      margin: 0;
      border: 0;
      padding: 0;
      width: 100%;
      font-size:smaller;
    }
    #headerdiv{
      top: 0;
      left: 0;
      width: 100%;
      height: 10;
      opacity: 0;
      position:absolute;
    }
  </style>
</html>
